package com.my.concurrency.test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 通过 ReentrantLock 实现线程安全
 *
 * @author mars
 * @date 2025-02-27 04:16
 */
public class SafeCounterByReentrantLock {
    private long count = 0;

    private static final Lock lock = new ReentrantLock();

    private void add10k() {
        System.out.println(Thread.currentThread().getName() + " start.");
        lock.lock();
        try {
            int idx = 0;
            while (idx++ < 10000) {
                count += 1;
            }
        } finally {
            lock.unlock();
        }
        System.out.println(Thread.currentThread().getName() + " end.");
    }

    public static void main(String[] args) {
        SafeCounterByReentrantLock counter = new SafeCounterByReentrantLock();
        Thread th1 = new Thread(counter::add10k);
        Thread th2 = new Thread(counter::add10k);

        th1.start();
        th2.start();

        try {
            // 等待 th1 和 th2 两个线程结束
            th1.join();
            th2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 输出结果是 20000
        System.out.println("The result is : " + counter.count);
    }
}
